package com.totcy.controller;

import com.totcy.constant.CommonConstant;
import com.totcy.constant.exception.MyIllegalArgumentException;
import com.totcy.model.User;
import com.totcy.service.IUserService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ResponseBody
    @RequestMapping("/showUser.do")
    public JSONObject selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if ("".equals(request.getParameter("email"))) {
            throw new MyIllegalArgumentException(CommonConstant.ErrorCode.CODE1002);
        }
        return this.userService.selectUser(request.getParameter("email"));
    }

    @ResponseBody
    @RequestMapping("/register.do")
    public JSONObject register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if ("".equals(request.getParameter("email")) || "".equals(request.getParameter("password"))) {
            throw new MyIllegalArgumentException(CommonConstant.ErrorCode.CODE1002);
        }
        User user = new User();
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        user.setUserName("用户" + System.nanoTime() % 100);
        user.setRegisterIp("172.0.0.1");
        return this.userService.register(user);
    }

    @ResponseBody
    @RequestMapping("/login.do")
    public JSONObject login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if ("".equals(request.getParameter("email")) || "".equals(request.getParameter("password"))) {
            throw new MyIllegalArgumentException(CommonConstant.ErrorCode.CODE1002);
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("email", request.getParameter("email"));
        params.put("password", request.getParameter("password"));
        return this.userService.login(params);
    }
}
